<?php $this->load->view('header'); ?>

<!-- Common Styles for the application --> 
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>application/resources/css/silk.css" />

<!-- overrides to base library --> 
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/css/GridFilters.css" /> 
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/css/RangeMenu.css" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>application/resources/js/ext_plugins/fileuploadfield/css/fileuploadfield.css"/> 
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>application/resources/js/ext_plugins/css/RowEditor.css"/>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>application/resources/js/ext_plugins/css/MultiSelect.css"/>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>application/resources/js/ext_plugins/css/LockingGridView.css"/>
<!-- extensions section -->

<!-- Grid filters plugin -->
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/menu/RangeMenu.js"></script> 
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/menu/ListMenu.js"></script> 

<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/GridFilters.js"></script> 
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/filter/Filter.js"></script> 
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/filter/StringFilter.js"></script> 
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/filter/DateFilter.js"></script> 
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/filter/ListFilter.js"></script> 
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/filter/NumericFilter.js"></script> 
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/gridfilters/filter/BooleanFilter.js"></script> 
 
<!-- Row editor plugin -->
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/RowEditor.js"></script>

<!-- Locking grid plugin -->
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/LockingGridView.js"></script>



<!-- FileUpload field plugin -->
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/fileuploadfield/FileUploadField.js"></script>

<!-- ItemSelector plugin -->
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/MultiSelect.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/ItemSelector.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/SearchField.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/ext_plugins/printer/Printer-all.js"></script>

<!-- end extensions section -->



<!-- my application -->
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/application/DocumentGrid.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/application/DocumentForm.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/application/UserManager.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/application/WhoIsOnline.js"></script>

<!-- scripts to handle the form validation and md5 password encode -->
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/application/form_validation.js"></script>

<!-- the jshash library used to apply an MD5 to the password types by the user when a user is created -->
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/jshash-2.2/md5-min.js"></script>

<!-- Window Reports -->
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/application/reports/getDocumentList.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/application/reports/windowReports_byDocumentType.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>application/resources/js/application/reports/jasperReportManager.js"></script>

<script type="text/javascript">
//Application instance for showing user-feedback messages.

// print css path file
Ext.ux.Printer.BaseRenderer.prototype.stylesheetPath = 'application/resources/js/ext_plugins/printer/print.css';

Ext.onReady( function() {
	myApp.setAlert(myApp.STATUS_NOTICE, '<b><i>' + myApp.userdata.username + '</i></b><br/>Bienvenido a la secci&oacute;n administrativa');
});

cloneConfig = function (config) { 
	for (i in config) {
		if (typeof config[i] == 'object') { 
			this[i] = new cloneConfig(config[i]);
		} 
		else
			this[i] = config[i];
	}
};

//-------------------------------------------
// documentForm object initialization section

//create document.Form instance (@see assests/js/application/DocumentForm.js )
var documentForm = new App.document.Form({
    //renderTo: 'user-form',
    bodyStyle:'padding:5px 3px 5px 5px',
    application: myApp,

    // If set to true, reset() resets to the last loaded or setValues() data instead of when the form was first created. 
    // Defaults to false.
    trackResetOnLoad: true, 
    
    listeners: {
        create : function(fpanel, data) {   // <-- custom "create" event defined in App.document.Form class
            var rec = new documentGrid.store.recordType(data);
            documentGrid.store.add(rec);
        }
    }
});

//-------------------------------------------
// grid object initialization section

var documentRecord = Ext.data.Record.create([
	{name: 'id',  mapping: 'id'	},
	{name: 'authors',  mapping: 'authors'	}, 
	{name: 'title',  mapping: 'title'}, 
	{name: 'documentType',  mapping: 'documentType'},
	{name: 'year',  mapping: 'year'}, 
	{name: 'pages',  mapping: 'pages'},
	{name: 'publishedin',  mapping: 'publishedin'},
  {name: 'abstract',  mapping: 'abstract'},
  {name: 'keywords',  mapping: 'keywords'},
  {name: 'created_at',  mapping: 'created_at'},
  {name: 'updated_at',  mapping: 'updated_at'},
	//
  {name: 'files',  mapping: 'files'}
]);

// configuring the grid filter
var filters = new Ext.ux.grid.GridFilters({
    // encode and local configuration options defined previously for easier reuse
    encode: false, // json encode the filter query
    local: myApp.filterType,   // defaults to false (remote filtering)
    menuFilterText: 'Filtrar',
    filters: [{
        type: 'numeric',
        dataIndex: 'id'
    }, {
        type: 'string',
        dataIndex: 'authors'
        //disabled: true
    }, {
        type: 'string',
        dataIndex: 'title'
    }, {
        type: 'list',
        dataIndex: 'documentType',
        options: [
        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_THESIS, 						myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_THESIS],
        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MASTER_THESIS, 		myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_MASTER_THESIS],
        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_PHD_THESIS, 				myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_PHD_THESIS],
        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE, 	myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE],
        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_BOOK, 							myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_BOOK],
        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA, 			myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA]
        ],
        phpMode: true
    }, {
    		type: 'string',
        dataIndex: 'year'
    }, {
    		type: 'string',
        dataIndex: 'pages'
    }, {
    		type: 'string',
        dataIndex: 'publishedin'
    }, {
    		type: 'string',
        dataIndex: 'abstract'
    }, {
        type: 'string',
        dataIndex: 'keywords'
    }]
});  

//Create HttpProxy instance.  Notice new configuration parameter "api" here instead of load.  However, you can still use
//the "url" paramater -- All CRUD requests will be directed to your single url instead.
var documentProxy = new Ext.data.HttpProxy({
  api: {
		read: BASE_URL + 'documents',
		create: BASE_URL + 'documents/create', 
		update: BASE_URL + 'documents/update',
		destroy: BASE_URL + 'documents/delete'
	},
	method: 'POST'
});

//Typical JsonReader.  Notice additional meta-data params for defining the core attributes of your json-response
var documentReader = new Ext.data.JsonReader({
    totalProperty: 'documents',
    successProperty: 'success',
    messageProperty: 'message',  // <-- New "messageProperty" meta-data
    idProperty: 'id',
    root: 'data',
    fields: documentRecord
});

// The new DataWriter component.
var documentWriter = new Ext.data.JsonWriter({
    encode: true,
    writeAllFields: false
});

//Typical Store collecting the Proxy, Reader and Writer together.
var documentGroupingStore = new Ext.data.GroupingStore({
		proxy: documentProxy,
    reader: documentReader,
    writer: documentWriter, // <-- plug a DataWriter into the store just as you would a Reader
    sortInfo:{field: 'created_at', direction: "DESC"},
    //sortInfo:{field: 'id', direction: "DESC"},
    groupField:'documentType',
    autoSave: true // <-- false would delay executing create, update, destroy requests until specifically told to do so with some [save] buton.
});

// load the store immeditately
documentGroupingStore.load();

/**
 * Handler for the documentType column renderer
 * @param {Object} value
 */ 
function documentTypeRenderer(value) {
	var documentType = parseInt(value);
	
	switch (documentType) {
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_THESIS: 
			return myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_THESIS;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MASTER_THESIS: 
			return myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_MASTER_THESIS;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_PHD_THESIS: 
			return myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_PHD_THESIS;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE: 
			return myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE;

		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_BOOK: 
			return myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_BOOK;

		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA: 
			return myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA;
	}
}

// Let's pretend we rendered our grid-columns with meta-data from our ORM framework. 
// In our case documents doctrine record
// {data source} == mapping ==> {data store} == dataIndex ==> {ColumnModel}
var columnModel = new Ext.grid.ColumnModel([
	{header: "Id", dataIndex: 'id', sortable: true, filterable: true, hidden: true},
	{header: "Autor", width: 120, dataIndex: 'authors', sortable: true, filterable: true},
	{header: "T&iacute;tulo", width: 180, dataIndex: 'title', sortable: true, filterable: true},
	{header: "A&ntilde;o", width: 115, dataIndex: 'year', sortable: true, filterable: true},
	{header: "P&aacute;ginas", width: 100, dataIndex: 'pages', sortable: true},
	{header: "Publicado en", width: 100, dataIndex: 'publishedin', sortable: true, filterable: true},
	{header: "Adicionado", width: 100, dataIndex: 'created_at', sortable: true, renderer: formatDateRenderer},
	{header: "Tipo de Documento", width: 100, dataIndex: 'documentType', sortable: true, renderer: documentTypeRenderer, filterable: true}
]);

//create document.Grid instance (@see assests/js/application/DocumentGrid.js)
var documentGrid = new App.document.Grid({
		id: 'mainGrid',
    store: documentGroupingStore,
    cm: columnModel,
		sm: new Ext.grid.RowSelectionModel({ 
			singleSelect: true
		}),
		application: myApp,
		linkedForm: documentForm,
		loadMask: true, 
		showConfigPanel: true,

		// group view to visualize the header in each group
		view: new Ext.grid.GroupingView({
    	forceFit:true,
      groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Documentos" : "Documento"]})',
      showGroupsText: 'Mostrar en Grupos',
      groupByText: 'Agrupar por este Campo',
      columnsText: 'Columnas',
      sortAscText: 'Ordena Ascedentemente',
      sortDescText: 'Ordenar Descendentemente',
      listeners: {
        // delegate this event to select the new added document to the grid  
        rowupdated : function( view,  firstRow, record ) {
          view.grid.getSelectionModel().selectFirstRow();
        }
      }
    }),

    // add the plugin filters to the grid
    plugins: [filters],

    listeners: {
        destroy : function() {
        	documentForm.getForm().reset();
        }
    }

});

// link the grid and form together
documentForm.setLinkedGrid(documentGrid);

// end of grid initialization section
//------------------------------------------------

// declaracion y definicion de la barra principal de sismapc
var mainToolBar = new Ext.Toolbar({
    items: [
				{
					xtype: 'buttongroup', 
					title: 'Documentos', 
					columns: 2, 
					defaults: {
						scale: 'small'
					},
					items: [{
	            text: 'Adicionar',
	            iconCls: 'silk-page-white-add',
	            handler: documentGrid.onAdd,
	            scope: documentGrid
		        }, {
	            text: 'Eliminar',
	            iconCls: 'silk-page-white-delete',
	            handler: documentGrid.onDelete,
	            scope: documentGrid
			    }] 
				}, {
					xtype: 'buttongroup', 
					title: 'Reportes', 
					columns: 2, 
					defaults: {
						scale: 'small'
					},
					items: [{
	            xtype:'splitbutton',
              text: 'De ventana',
              iconCls: 'silk-report',
              menu: new Ext.menu.Menu({
                  items: [{	
              	      text: 'Mostrar tipos de documentos',
                    	handler: getDocumentList
            	        //scope: documentGrid
            	      }, { 
                	    text: 'Mostrar documentos por Tipo de Documento',
											handler: getDocuments
                    }
                  ]
             	})
              
		        }, {
	            text: 'Jasper',
	            iconCls: 'silk-report-link',
	            handler: showJasperReportDialog
			    }] 
				}, {
					xtype: 'buttongroup', 
					title: 'Usuarios', 
					columns: 3, 
					defaults: {
						scale: 'small',
	          width: '100%',
	          iconAlign: 'left'
					},
					items: [{
							text: 'Administraci&oacuten de Usuarios',
			        iconCls: 'user-edit',
	            handler: function() {
			          if( !myApp.userDialog ) {
			        	  myApp.userDialog = new App.user.UserManager({
			        			application: myApp
			        		});
				        }  
	            	myApp.userDialog.show();
	            }
						}, {
							text: 'Usuarios online?', 
							iconCls: 'icon-user',
							handler: function() {
						  	if( !myApp.whoIsOnlineDialog ) {
						    	myApp.whoIsOnlineDialog = new App.user.WhoIsOnline({
							    	application: myApp
						      });
							  }  
						  	myApp.whoIsOnlineDialog.show();
				      }
						}] 
				}, '->', {
	        iconCls: 'icon-user-logout',
	        text: 'Cerrar sesi&oacute;n ' + myApp.userdata.username,
	        handler: doLogout,
	        height: 43,
	        tooltip: 'Click sobre este bot&oacute;n para cerrar la sesi&oacute;n del usuario <b>' + myApp.userdata.username + '</b>'
    }]
});

var documentTabPanel = new Ext.TabPanel({
		id:'documentTabPanel',
    border: false, // already wrapped so don't add another border
    activeTab: 0, // second tab initially active
    defaults:{autoWidth: true, autoHeight:true, bodyStyle:'padding:5px'},
    autoScroll: true,
    items: [documentForm]
});

var viewport = new Ext.Viewport({
	layout: 'border', 
	renderTo: Ext.getBody(),
	items: [ 
  	{ region: 'north', 
  	 	autoHeight: true, 
  	 	height: 100, 
  	 	border: false,
      html: '<div id="header">SISMAPC <span style="font-size:12px;">Sistema para la gestion de la Producci&oacute;n Cient&iacute;fica en la UNISS.</span></div>',
      margins: '0 0 5 0', 
      style: 'border-bottom: 4px solid #4c72a4;' 
    }, {
    	region: 'east',
        collapsible: true,
        collapsed: true,
        split: true,
        width: 400, // give east and west regions a width
        minSize: 175,
        maxSize: 600,
        margins: '0 5 5 0',
        padding: '0 0 0 0',
        layout: 'fit', // specify layout manager for items
        items: documentTabPanel           // this TabPanel is wrapped by another Panel so the title will be applied
        
    }, {
    	id: 'content-panel', 
    	region: 'center', 
    	layout: 'fit', 
    	margins: '0 0 5 5',
      //activeItem: 0, 
      //border: true, 
      tbar:mainToolBar, 
      items: [documentGrid]
    }
  ]});

//centralized listening of DataProxy events "beforewrite", "write" and "writeexception"
//upon Ext.data.DataProxy class.  This is handy for centralizing user-feedback messaging into one place rather than
//attaching listenrs to EACH Store.
//
//Listen to all DataProxy beforewrite events
//
Ext.data.DataProxy.addListener('beforewrite', function(proxy, action) {
	myApp.setAlert(myApp.STATUS_NOTICE, "Ejecuntando la acci&oacute;n: " + action);
});

/*
Ext.data.DataProxy.addListener('load', function(proxy, action) {
	myApp.setAlert(App.STATUS_NOTICE, "Before " + action);
});
*/

//all write events
//
Ext.data.DataProxy.addListener('write', function(proxy, action, result, res, rs) {
	if( /*action == "update" || */action == "create" ) {
/*
		documentGrid.store.reload({
			action: action, record: result[0]
			});
		*/	
	}
	myApp.setAlert(myApp.STATUS_OK, action + ': ' + res.message);
});

//all exception events
//
Ext.data.DataProxy.addListener('exception', function(proxy, type, action, options, res) {
	myApp.setAlert(App.STATUS_ERROR, "Algo err&oacute;neo ha ocurrido mientras se executaba la acci&oacute;n: " + action + "<br/>" + res.message);
});

// Customize the default text for MessageBox
Ext.MessageBox.buttonText.yes = 'Si';
Ext.MessageBox.buttonText.cancel = 'Cancelar';

viewport.show();
</script>

<?php $this->load->view('footer'); ?>